package org.bluedream.core.module.service.stock;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.annotations.Param;
import org.bluedream.comm.utils.EmptyUtil;
import org.bluedream.comm.utils.RestResult;
import org.bluedream.comm.utils.excel.ExcelUtil;
import org.bluedream.core.module.base.OrgBaseServiceImpl;
import org.bluedream.core.module.dao.stock.SkuStockDao;
import org.bluedream.core.module.entity.stock.SkuStock;
import org.bluedream.core.module.entity.stock.TmpSkuStock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SkuStockService
 * @Description TODO
 * @Author foxsand
 * @Data 2021-11-15 10:32
 * @Version
 */
@Service
@DS("master")
@Transactional(
        readOnly = true
)
public class SkuStockService extends OrgBaseServiceImpl<SkuStockDao, SkuStock> implements IService<SkuStock> {
    private static final Logger logger = LoggerFactory.getLogger(SkuStockService.class);

    @Transactional(
            isolation = Isolation.SERIALIZABLE
    )
    @Override
    public SkuStock getById(Serializable id) {
        if (EmptyUtil.isEmpty(id)){
            return new SkuStock();
        }
        return super.getById(id);
    }

    @Transactional(
            isolation = Isolation.SERIALIZABLE
    )
    public SkuStock getByCode(String code){
        try {
            QueryWrapper<SkuStock> qw = new QueryWrapper<>();
            qw.eq("code" , code);
            return super.getOne(qw);
        }catch (Exception e1){
            e1.printStackTrace();
        }
        return null;
    }

    public IPage<SkuStock> findPage(SkuStock entity, String... args) {
        try {
            Map<String , Object> search = null;
            search = new HashedMap();
            if (EmptyUtil.isEmpty(entity)){
                return null;
            }else if (EmptyUtil.isNoEmpty(entity.getCode())
                    || EmptyUtil.isNoEmpty(entity.getWarCode())
            ){
                if (EmptyUtil.isNoEmpty(entity.getCode())){
                    search.put("skuStock.code;eq" , entity.getCode());
                }
                if (EmptyUtil.isNoEmpty(entity.getWarCode())){
                    search.put("skuStock.war_code;eq" , entity.getWarCode());
                }
            }
            return super.findPage(entity , true , search , args);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }

    @Transactional(
            readOnly = false,
            isolation = Isolation.SERIALIZABLE,
            rollbackFor = Exception.class
    )
    @Override
    public boolean save(SkuStock entity) {
        return super.save(entity);
    }

    @Transactional(
            readOnly = false,
            isolation = Isolation.SERIALIZABLE
    )
    public BigDecimal getNowSkuStockQty(String loginOrgCode , String warCode , String code){
        return baseMapper.getNowSkuStockQty(loginOrgCode , warCode , code);
    }

    @Transactional(
            readOnly = false,
            isolation = Isolation.SERIALIZABLE
    )
    public TmpSkuStock getProductSumData(String loginOrgCode , String warCode , String code){
        return baseMapper.getProductSumData(loginOrgCode , warCode , code);
    }

    @Transactional(
            readOnly = false,
            isolation = Isolation.SERIALIZABLE,
            rollbackFor = Exception.class
    )
    public boolean saveByBill(QueryWrapper<SkuStock> queryWrapper , String type , String code , String warCode , BigDecimal qty , BigDecimal total){
        try {
            SkuStock ws = super.getOne(queryWrapper);
            if (EmptyUtil.isEmpty(ws)){
                ws = new SkuStock();
            }
            BigDecimal _qty = new BigDecimal("0");
            ws.setOprice(new BigDecimal("0"));
            if (type.equals("1")){
                _qty = ws.getQty().add(qty);
                if (EmptyUtil.isNoEmpty(ws.getTotal())){
                    ws.setTotal(ws.getTotal().add(total));
                }else {
                    ws.setTotal(total);
                }

                if (_qty.compareTo(new BigDecimal("0")) != 0){
                    ws.setOprice(ws.getTotal().divide(_qty));
                }
            }else if (type.equals("0")){
                _qty = ws.getQty().subtract(qty);

/*                if (_qty.compareTo(new BigDecimal("0")) < 0){
                    throw new RuntimeException("不允许负库存出库，请确认！");
                }*/

                if (EmptyUtil.isNoEmpty(ws.getTotal())){
                    ws.setTotal(ws.getTotal().subtract(total));
                }else {
                    ws.setTotal(new BigDecimal(0).subtract(total));
                }

                if (_qty.compareTo(new BigDecimal("0")) != 0){
                    ws.setOprice(ws.getTotal().divide(_qty));
                }
            }
            ws.setWarCode(warCode);
            ws.setQty(_qty);
            ws.setCode(code);
            return save(ws);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            //todo:@Transactional和try catch捕获异常会让注解失效
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    public void fileDownload(HttpServletRequest request, HttpServletResponse resp, SkuStock entity){
        try {
            QueryWrapper<SkuStock> qw = new QueryWrapper<>();
            qw.eq("1" , "1");
            if (EmptyUtil.isNoEmpty(entity.getCode())){
                qw.like("code" , entity.getCode());
            }
            if (EmptyUtil.isNoEmpty(entity.getWarCode())){
                qw.like("ware_code" , entity.getWarCode());
            }
            List<SkuStock> skuStocks = super.list(qw);
            ExcelUtil.export4List(resp , skuStocks , SkuStock.class , "exportFileName" , "exportSheetName" , "测试Excel文件导出");
        }catch (Exception e){
            e.getMessage();
        }
    }
}
